package com.woniuxy.filters;

import com.woniuxy.entity.User;
import com.woniuxy.enums.TokenStatusEnum;
import com.woniuxy.jwt.JWTUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class JWTGlobalFilter implements GlobalFilter, Ordered {
    @Resource
    RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        List<String> authorization=exchange.getRequest().getHeaders().get("Authorization");
        List<String> refreshTokenList=exchange.getRequest().getHeaders().get("refreshTokenList");
        if(authorization!=null && refreshTokenList!=null){
            String token=authorization.get(0);
            String refreshToken=refreshTokenList.get(0);
            TokenStatusEnum verify= JWTUtils.verify("token");
            if (verify.equals(TokenStatusEnum.TOKEN_SUCCESS)){
                return chain.filter(exchange);
            }else if(verify.equals(TokenStatusEnum.TOKEN_EXPIRE)){
               User user = (User) redisTemplate.opsForValue().get(refreshToken);
               if(user==null){
                   return Mono.error(new ArithmeticException("长时间未操作，请重新登录"));
               }else{
                    String newJwt=JWTUtils.generateToken(user.getUsername());
                    exchange.getRequest().getHeaders().add("token",newJwt);
                    redisTemplate.expire(refreshToken,60, TimeUnit.MINUTES);
                    return chain.filter(exchange);
               }
            }else{
                redisTemplate.delete(refreshToken);
                return Mono.error(new ArithmeticException("token被篡改，请重新登录"));
            }
        }else{
            if ("/auth/login".equals(exchange.getRequest().getPath().toString())) {
                return chain.filter(exchange);
            }else {

            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
